package com.cicadasmall.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicadasmall.common.base.BaseService;
import com.cicadasmall.common.exception.ServiceException;
import com.cicadasmall.data.domain.MenuDO;
import com.cicadasmall.data.domain.RoleMenuDO;
import com.cicadasmall.data.mapper.SysRoleMenuMapper;
import com.cicadasmall.system.service.IMenuService;
import com.cicadasmall.system.service.IRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色菜单表 服务实现类
 * </p>
 *
 * @author westboy
 * @date 2019-07-21
 */
@Service
public class RoleMenuServiceImpl extends BaseService<SysRoleMenuMapper, RoleMenuDO> implements IRoleMenuService {
    @Autowired
    private IMenuService menuService;



    @Override
    public void updateRoleMenu(Integer roleId, List<String> permissionIds) {
        if (CollectionUtil.isNotEmpty(permissionIds)) {

            LambdaQueryWrapper lambdaQueryWrapper = getLambdaQueryWrapper().eq(RoleMenuDO::getRoleId, roleId);
            Integer counter = baseMapper.selectCount(lambdaQueryWrapper);

            if (counter > 0) {
                baseMapper.delete(lambdaQueryWrapper);
            }

            permissionIds.forEach(id -> {
                MenuDO menuDO = menuService.getById(id);
                if (menuDO == null) {
                    throw new ServiceException("资源不存在! id-" + id);
                }
                RoleMenuDO roleMenuDO = new RoleMenuDO();
                roleMenuDO.setMenuId(menuDO.getMenuId());
                roleMenuDO.setRoleId(roleId);
                save(roleMenuDO);
            });

        }
    }


}
